import React, { Component } from "react";

export default class IndexList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contentHtml: "",
      navHtml: "",
    };
    this.content = document.querySelector("#content");
    this.nav = document.querySelector("#nav");
    this.navList = document.querySelector("#navList");
    this.indicator = document.querySelector("#indicator");
    this.currentHeight = "";
    this.navOffsetX = 0;
    this.indicatorTime = null;
    this.firstSection = null;
    this.moving = false;
    this.sections = [];
    this.currentIndicator = "";
  }

  /**滚动左侧列表 */
  scrollTheList = (y) => {
    console.log("scrollTheList");
    var currentItem = document.elementFromPoint(this.navOffsetX, y);
    if (!currentItem || !currentItem.classList.contains("indexlist-navitem")) {
      return;
    }
    this.currentIndicator = currentItem.innerText;
    this.indicatorRef.innerText = this.currentIndicator;
    this.indicatorRef.style.display = "";

    var targets = [].slice.call(this.sections).filter(function (section) {
      var index = section.getAttribute("data-index");
      return index === currentItem.innerText;
    });
    var targetDOM;
    if (targets.length > 0) {
      targetDOM = targets[0];
      this.contentRef.scrollTop =
        targetDOM.getBoundingClientRect().top -
        this.firstSection.getBoundingClientRect().top;
      // targetDOM.scrollIntoView();
    }
  };

  /**开始触摸 */
  handleTouchstart = (e) => {
    if (e.target.tagName !== "LI") {
      return;
    }

    this.navOffsetX = e.changedTouches[0].clientX;
    console.log(e.changedTouches[0].clientY);
    this.scrollTheList(e.changedTouches[0].clientY);
    // this.scrollTheList();
    if (this.indicatorTime) {
      clearTimeout(this.indicatorTime);
    }
    this.moving = true;
    window.addEventListener("touchmove", this.handleTouchMove, {
      passive: false,
    });
    window.addEventListener("touchend", this.handleTouchEnd);
  };

  /**滑动 */
  handleTouchMove = (e) => {
    e.preventDefault();
    this.scrollTheList(e.changedTouches[0].clientY);
  };

  /**停止触摸 */
  handleTouchEnd = (e) => {
    this.indicatorTime = setTimeout(() => {
      this.moving = false;
      this.currentIndicator = "";
      this.indicatorRef.style.display = "none";
      this.indicatorRef.innerText = this.currentIndicator;
    }, 500);
    window.removeEventListener("touchmove", this.handleTouchMove);
    window.removeEventListener("touchend", this.handleTouchEnd);
  };
  checkbox = (e) => {
    console.log(e);
  };

  /**初始化DOM */
  initialDOM = () => {
    var data = this.props.data;
    var contentHtml = "";
    var navHtml = "";
    // 初始化内容和NAV
    function arrayBufferToBase64(buffer) {
      var binary = "";
      var bytes = new Uint8Array(buffer);
      var len = bytes.byteLength;
      for (var i = 0; i < len; i++) {
        binary += String.fromCharCode(bytes[i]);
      }
      return window.btoa(binary);
    }
    data.forEach(function (d) {
      var index = d.title;
      var items = d.items;
      navHtml += '<li class="indexlist-navitem">' + index + "</li>";
      contentHtml +=
        '<li class="indexsection" data-index="' +
        index +
        '"><p class="indexsection-index">' +
        index +
        "</p><ul>";
      items.forEach(function (item) {
        contentHtml +=
          '<a class="cell"><input class="select" id = "' +
          item.id +
          "_" +
          item.name +
          '" type="checkbox" ><label for="' +
          item.id +
          "_" +
          item.name +
          '"><div class="cell-img"><img src="data:image/png;base64,' +
          arrayBufferToBase64(item.photo) +
          '" ></div><div class="cell-wrapper"><div class="cell-title"><span class="cell-text">' +
          item.name +
          '</span></div><div  class="cell-text"> <span class="cell-text">' +
          item.signature +
          "</span></div></div></label></a>";
      });
      contentHtml += "</ul></li>";
    });
    // this.setState({
    //   contentHtml: contentHtml,
    //   navHtml: navHtml,
    // });
    this.contentRef.innerHTML = contentHtml;
    this.navListRef.innerHTML = navHtml;
  };

  // mounted() {
  //   var currentHeight, navWidth;

  //   this.initialDOM();

  //   if (!currentHeight) {
  //     currentHeight =
  //       document.documentElement.clientHeight -
  //       this.contentRef.getBoundingClientRect().top;
  //   }
  //   navWidth = this.navRef.clientWidth;
  //   this.contentRef.style.marginRight = navWidth + "px";
  //   this.contentRef.style.height = currentHeight + "px";

  //   this.sections = this.contentRef.getElementsByTagName("li");
  //   this.firstSection = this.sections[0];
  // }

  setContentRef = (ref) => {
    this.contentRef = ref;
  };
  setNavRef = (ref) => {
    this.navRef = ref;
  };
  setNavListRef = (ref) => {
    this.navListRef = ref;
  };
  setIndicatorRef = (ref) => {
    this.indicatorRef = ref;
  };

  componentDidMount() {
    var body = document.querySelector("body");
    body.className = "indexList";
    var currentHeight, navWidth;

    this.initialDOM();

    if (!currentHeight) {
      currentHeight =
        document.documentElement.clientHeight -
        this.contentRef.getBoundingClientRect().top;
    }
    navWidth = this.navRef.clientWidth;
    this.contentRef.style.marginRight = navWidth + "px";
    this.contentRef.style.height = currentHeight + "px";

    this.sections = this.contentRef.getElementsByTagName("li");
    this.firstSection = this.sections[0];

    // document.addEventListener("DOMContentLoaded", this.mounted);
    this.navRef.addEventListener("touchstart", this.handleTouchstart);
  }

  render() {
    return (
      <div className="indexlist">
        <ul className="indexlist-content" id="content" ref={this.setContentRef}>
          {/* {contentHtml} */}
        </ul>
        <div className="indexlist-nav" id="nav" ref={this.setNavRef}>
          <ul
            className="indexlist-navlist"
            id="navList"
            ref={this.setNavListRef}
          >
            {/* {navHtml} */}
          </ul>
        </div>
        <div
          className="indexlist-indicator"
          style={{ display: "none" }}
          id="indicator"
          ref={this.setIndicatorRef}
        ></div>
      </div>
    );
  }
}
